import routerConfig from "@/common/routerConfig.js"

const getSystemInfo = (vm) => {
	uni.getSystemInfo({
		success: function(e) {
			const statusBarHeight = e.statusBarHeight
			let custom = uni.getMenuButtonBoundingClientRect()
			const customBarHeight = (custom.top - statusBarHeight) * 2 + custom.height
			vm.$u.vuex('systemInfo', {
				customBarHeight,
				statusBarHeight,
				screenHeight: e.screenHeight,
				screenWidth: e.screenWidth
			})
		}
	})
}


const setDefaultData = () => {
	// 是否显示视频详情中的提示
	if (uni.getStorageSync('showVideoGuide') === undefined) {
		uni.setStorageSync('showVideoGuide', true)
	}
}



const initRouterInterceptor = (vm) => {
	const {
		needLogin,
		visitor,
		loginPattern,
	} = routerConfig //需要登录的页面
	let list = ["navigateTo", "redirectTo", "reLaunch", "switchTab"];

	// 路由跳转时触发
	list.forEach(item => {
		uni.addInterceptor(item, {
			invoke(e) {
				const token = vm.accessToken,
					isBindDms = vm.isBindDms,
					url = e.url.split('?')[0];
				const pages = getCurrentPages();
				if (!pages.length) {
					return e
				}
				const fromUrl = pages[pages.length - 1].route;

				let inSamePage = fromUrl.replace('/', '') === url.replace('/', '')
				if (
					loginPattern.test(url) &&
					!inSamePage
				) {
					return e
				} else {
					let pass = true
					if (visitor) {
						pass = visitor.some((item) => {
							if (typeof(item) == 'object' && item.pattern) {
								return item.pattern.test(url)
							}
							return url == item
						})
					}
					
					if (needLogin) {
						pass = needLogin.every((item) => {
							if (typeof(item) == 'object' && item.pattern) {
								return !item.pattern.test(url)
							}
							return url != item
						})
					}
					

					if (!pass && !token) {
						// uni.showToast({
						// 	title: '请先登录',
						// 	icon: 'none'
						// })
						vm.$u.route({
							url: '/pages/login/login'
						})
						return false
					}

				}
				return e
			},
			fail(err) {
				console.log(err)
			}
		})
	})




}


export default function(vm) {


	// 获取系统数据
	getSystemInfo(vm)
	
	//自定义路由拦截
	initRouterInterceptor(vm)
	
	// 初始化数据
	setDefaultData(vm)
}
